var defaultCategory = {
    "id":"",
    "name":"",
    "infoUrl":"",
    "collect" : true,
    "shows" : true
}

var defaultStep = {
    "submit":false,
    "contestId":"",
    "showPosition":10,
    "showCount":1,
    "endTime":0,
    "quit":false,
    "shows":false,
    "startTime":0,
    "id":"",
    "showLabel":"",
    "name":"",
    "countDownTips":"",
    "tips":"",
    "showStyle":0,
    "defaultPage":0,
    "allowType" :0
};
var stepEnd = {
    "submit":false,
    "contestId":"",
    "showPosition":30,
    "showCount":1,
    "endTime":0,
    "quit":false,
    "shows":false,
    "startTime":0,
    "id":"",
    "showLabel":"",
    "name":"颁奖",
    "countDownTips":"",
    "tips":"",
    "showStyle":0,
    "defaultPage":1,
    "allowType" :0
}

cur_result = {
    "appUrl": {

    },
    "webUrl": {

    },
    "contestCategorys": [
        {
            "id":"",
            "name":"默认分类",
            "infoUrl":"",
            'collect' : true,
            'shows' : false
        }
    ],
    "resCategoryName" : [],
    "hostUnit": "",
    "appDetailUrl": {

    },
    "state": 0,
    "id": "",
    "title": "",
    "refer": "",
    "curStepId": "",
    "prizes": [],
    "webDetailUrl": {
    },
    "tags": "",
    "contestSteps": [
        {
            "submit":false,
            "contestId":"",
            "showPosition":10,
            "showCount":1,
            "endTime":0,
            "quit":false,
            "shows":false,
            "startTime":0,
            "id":"",
            "showLabel":"",
            "name":"",
            "countDownTips":"",
            "tips":"",
            "showStyle":0,
            "defaultPage":0,
            "allowType" :0
        },{
            "submit":false,
            "contestId":"",
            "showPosition":10,
            "showCount":1,
            "endTime":0,
            "quit":false,
            "shows":false,
            "startTime":0,
            "id":"",
            "showLabel":"",
            "name":"",
            "countDownTips":"",
            "tips":"",
            "showStyle":0,
            "defaultPage":0,
            "allowType" :0
        }, {
            "submit":false,
            "contestId":"",
            "showPosition":30,
            "showCount":1,
            "endTime":0,
            "quit":false,
            "shows":false,
            "startTime":0,
            "id":"",
            "showLabel":"",
            "name":"颁奖",
            "countDownTips":"结束时间",
            "tips":"",
            "showStyle":0,
            "defaultPage":1,
            "allowType" :0
        }
    ],
    "contestStepInfo": {},
    "recommendation": 1,
    "rating" : 0,
    "contestPropertyInfo": {
        "sameTypeCount": 0,
        "id": "",
        "hiddenAll": false,
        "stepCount": 0,
        "hiddenRating": false,
        "createdTime": 0,
        "otherDescr": "",
        "categoryCount": 0,
        "infoCollectUrl": "",
        "prizeCount": 0,
        "intro": "",
        "infoCollect": false
    },
    "background":"",
    "contestType":0
}



$(function(){
    $('.form_datetime').datetimepicker({
        initialDate : new Date(new Date().setSeconds(0)),
        language:  'zh-CN',
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        //minView : 2,
        forceParse: 0,
        showMeridian: 0
    });


})


navbarApp.controller('config_contest_controller', function ($scope, $http) {
        /**
         * 大赛类别
         */

        /*添加分类*/
        /*$scope.add_line = function(){
            var a = $('<div class="form-group txt-left cate-group">' +
                '<div class="col-lg-2">'+
                '<input class="form-control" type="text">'+
                '</div>'+
                '<div class="col-lg-5">'+
                '<input class="form-control" type="text">'+
                '</div>'+
                '<div class="col-lg-1">'+
                '<button type="button" class="btn btn-default delete-action" ng-click="delete_line($event.target)">-</button>'+
                '</div>'+
                '</div>')

            a.find('.delete-action').click(function(){
                $(this).parents(".cate-group").remove();
            });
            $(".cate-grid").append(a);

            /*angular.element(document.body).injector().invoke(function ($compile) {
             var scope = angular.element(a).scope();
             $compile(a)(scope);
             scope.$digest();
             });*/

       /* }
        $scope.delete_line = function(obj){
            $(obj).parents(".cate-group").remove();
        }*/



    $scope.initTime = function(){
        $('.form_datetime').datetimepicker({
            initialDate : new Date(new Date().setSeconds(0)),
            language:  'zh-CN',
            weekStart: 1,
            todayBtn:  1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            //minView : 2,
            forceParse: 0,
            showMeridian: 0
        });
    }

    var catesParObj = [];


    $('#example-multiple-optgroups').multiselect({
        maxHeight: 200,
        nonSelectedText: '没有选择分类',
        nSelectedText: '个分类已选',
        allSelectedText: '全部',
        onChange : function(option, checked){
            var cateVal = option[0].value;
            var cateLargeVal = $(option[0]).data('parent');

            //var cateLargeVal = $($('.multiselect-container li.active').prev()[0]).find('label b').html();
            //console.log($($('.multiselect-container li.active').prev()[0]).find('label b').html());

            $scope.$apply(function(){
                if(checked){
                    $("#contest-tags").tagsinput('add', cateLargeVal);
                    $("#contest-tags").tagsinput('add', cateVal);
                    catesParObj.push(cateLargeVal);
                }else{
                    $("#contest-tags").tagsinput('remove', cateLargeVal);
                    $("#contest-tags").tagsinput('remove', cateVal);
                    for(var i=0; i<catesParObj.length; i++){
                        if(cateLargeVal == catesParObj[i]){
                            catesParObj.splice(i,1);
                            break;
                        }
                    }
                }
               // console.log($scope.result.tags);
               // console.log( $scope.result.resCategoryName);
            })
        }
    });


        $scope.init = function(contestId){
            var contestId = $.getUrlParam('contestId');
            if(!contestId){
                $scope.result = cur_result;
                console.log($scope.result);
                return false;
            }
            $.ajax({
                // 提交数据的类型 POST GET
                type : "post",
                // 提交的网址
                url : '/contests/contest/detail',
                // 提交的数据
                data : {
                    contestId : contestId
                },
                dataType : "json",// "xml", "html", "script", "json",
                success : function(data) {
                    if(data.status == '200'){
                        var cur_contest = data;
                        console.log(data);
                        $scope.$apply(function(){
                            if(typeof(cur_contest) != 'undefined'){
                                if (cur_contest instanceof Array && cur_contest.length) {
                                    $scope.result = cur_contest[0];
                                }else{
                                    //给要保存的分类里添加flag(edit:true)表示是已经保存过的分类，下次编辑的时候不让删除
                                    for(var i = 0,l= cur_contest.data.contestCategorys.length; i<l; i++){
                                        cur_contest.data.contestCategorys[i].edit = true;
                                    }
                                    console.log(cur_contest.data.contestCategorys);
                                    $scope.result = cur_contest.data;
                                }
                                if($scope.result.tags){
                                    var tags =  $scope.result.tags.split(',');
                                    for(var i = 0; i < tags.length; i++){
                                        $("#contest-tags").tagsinput('add', tags[i]);
                                    }
                                }
                                if($scope.result.state == -10){
                                    $scope.result.state = true;
                                }else{
                                    $scope.result.state = false;
                                }



                            }
                        });

                        $('#example-multiple-optgroups').multiselect('refresh');
                        $scope.$apply(function(){
                            $scope.initTime();
                        })

                    }else if(data.status == '302'){
                        layer.msg('您没有该权限');
                    }else{
                        layer.msg('服务器错误', {
                            icon: 1,
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                            //do something

                        });
                    }

                },
                error : function(e) {
                }
            });




        }



        /**
         * 时间规划
         */
        $scope.add_timeline = function(){
            var a = $($("#timeline-template").html());
            $(".timeline-list").append(a);
            a.find(".delete-action").click(function(){
                $(this).parents(".timeline-group").remove();
            });
        }
        $scope.delete_timeline = function(obj){
            $(obj).parents(".timeline-group").remove();
        }


    $scope.add_cate = function(){
        $scope.result.contestCategorys.push($.extend({},defaultCategory));
    }
    $scope.remove_cate = function(index) {
        $scope.result.contestCategorys.splice(index, 1);
    }

    $scope.add_time = function(){

        $scope.result.contestSteps.splice(($scope.result.contestSteps.length-1),0,$.extend({},defaultStep));
        $scope.$apply(function(){
            $scope.initTime();
        })
        $scope.initTime();
        /*$scope.result.contestSteps.push({
            "submit":false,
            "contestId":"",
            "showPosition":1,
            "showCount":1,
            "endTime":0,
            "quit":false,
            "shows":false,
            "startTime":0,
            "id":"",
            "showLabel":"",
            "name":"",
            "countDownTips":"",
            "tips":"",
            "showStyle":0,
            "defaultPage":0
        });*/
    }
    $scope.remove_time = function(index){
        $scope.result.contestSteps.splice(index, 1);
    }



    $scope.time_change = function(time_val,numFlag){
        if(!time_val){
            return '';
        }
        var curDate = new Date(time_val);
        if(numFlag){
            return curDate.getTime();
        }else{
            return curDate.pattern("yyyy-MM-dd HH:mm");
        }
    }



    //提交配置保存
    $scope.btn_submit = function(){

        var dd = angular.copy($scope.result);
        if(typeof(dd.state) == 'boolean'){
            if(dd.state){
                dd.state = -10;
            }else{
                delete dd.state;
            }
        }

        //去掉分类中为空的数据
        for(var a = 0; a<dd.contestCategorys.length; a++){
            if(!dd.contestCategorys[a].name){
                dd.contestCategorys.splice(a,1);
                a--;
            }
        }
        for(var a=0; a<dd.contestSteps.length; a++){
            if(!dd.contestSteps[a].name){
                dd.contestSteps.splice(a,1);
                a--;
            }else{
                dd.contestSteps[a].startTime = $scope.time_change(dd.contestSteps[a].startTime,true);
            }
        }


        console.log(dd.contestSteps);

        dd.resCategoryName = dd.resCategoryName.concat(catesParObj);

        console.log(dd);


        layer.confirm('确定保存?', {icon: 3, title:'提示'}, function(index){
            //do something

            var postData = {
                jsonData : sjApp.stringify(dd)
            }
            var contestId = $.getUrlParam('contestId');
            if(contestId){
                postData.contestId = contestId;
            }

            $.ajax({
                // 提交数据的类型 POST GET
                type : "post",
                // 提交的网址
                url : '/contests/contest/addContest',
                // 提交的数据
                data : postData,
                dataType : "json",// "xml", "html", "script", "json",
                success : function(data) {
                    if(data.status == '200'){
                        layer.msg('保存成功', {
                            icon: 1,
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){

                            //do something
                           // $("#dataTable").dataTable().fnDraw();
                        });
                    }else if(data.status == '302'){
                        layer.msg('您没有该权限');
                    }else{
                        layer.msg('请检查是否有遗漏的配置项未填写', {
                            icon: 1,
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                            //do something

                        });
                    }

                },
                error : function(e) {
                }
            });

            layer.close(index);
        });
    }


    $scope.init();














});